<template>
  <!--页面搭建-杜思成-->
  <layout-card v-model="search" :filters="ismapOptions" headline="信息列表" headtitle=" " :hasButton="true"
    @search-change="getData" @search-reset="searchReset">
    <table-common :height="tableHeight" :columns="mapListColumns" :loading="loading" :pagination="pager2"
      :table-data="tabledata" size="large" @current-change="changeCurrent2" @size-change="changePageSize2"
      @sort-change="sortChange">
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleAdd(row)" link type="primary">新建</el-button>
        <el-button class="link-btn" @click="handleView(row)" link type="primary">查看</el-button>
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary">编辑</el-button>
        <el-popconfirm title="是否删除?" confirmButtonText="确定" cancelButtonText="取消" @confirm="() => DeletRow(row)">
          <template #reference>
            <el-button class="link-btns" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>

  </layout-card>
  <!-- 新增/编辑弹窗开始 -->
  <el-dialog v-model="thresholdDialogVisible" :title="addTilte" width="850" center align-center>
    <span style="font-weight: bold">
      隐患清单:
    </span>
    <!--    <table-common-->
    <!--      :table-data="riskTableData"-->
    <!--      :columns="riskColumns"-->
    <!--      :pagination="earlyPager"-->
    <!--    ></table-common>-->
    <el-table ref="earlyTable" :data="riskTableData" :header-cell-style="{ background: 'rgb(245,245,245)' }" multiple
      stripe height="300" @select="selectChange" @row-click="rowClickHandle" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center"></el-table-column>
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="tshlId" label="隐患编号" width="200" align="center"></el-table-column>
      <el-table-column prop="tshlName" label="隐患名称" width="150" align="center"></el-table-column>
      <el-table-column prop="tshlClassify" label="隐患分类" width="150" align="center"></el-table-column>
      <el-table-column prop="tshlGrade" label="隐患等级" width="150" align="center"></el-table-column>
    </el-table>

    <el-pagination style="position: absolute; right: 30px" v-model:current-page="earlyPager.currentPage"
      v-model:page-size="earlyPager.pageSize" layout="prev, pager, next, sizes, jumper"
      v-model:page-count="earlyPager.pageCount" @size-change="changePageSize" @current-change="changeCurrent" />
    <div style="margin-left: 20px; margin-top: 80px; display: flex">
      <el-form-item label="评分标准：" required>
        <el-select v-model="assessInfo.tsharRules" :disabled="disabled" :placeholder="placeholder">
          <el-option @click="scoreStandardChange(item)" v-for="item in standards" :key="item.tsharRules"
            :label="item.rule" :value="item.tsharRules"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 60px" label="扣分值：" required>
        <el-input placeholder="根据选择的标准自动获取" disabled v-model="assessInfo.tsharScores"></el-input>
      </el-form-item>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="thresholdDialogVisible = false, earlySelect.value = []">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="primary" @click="thresholdDialogVisible = false">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 新增/编辑弹窗结束 -->
  <!-- 查看弹窗开始 -->
  <el-dialog v-model="viewDialogVisible" :title="addTilte" width="850" center align-center>
    <span style="font-weight: bold">
      隐患清单:
    </span>
    <table-common :table-data="riskTableData" :columns="earlyColumns" :pagination="pager"
      @current-change="changeCurrent3" @size-change="changePageSize3"></table-common>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

const earlyTable = ref();
const earlySelect = ref([])
const placeholder = ref("请先选择隐患清单")
const tableHeight = ref(window.innerHeight - 440)
const assessInfo = ref({
  // 评分标准
  tsharClassify: '',
  tsharGrade: '',
  tsharRules: '',
  tsharScores: '',
})

/**
 * @radioChange 评分标准下拉框的改变事件
 */
const scoreStandardChange = (event: any) => {
  // 选中自定义
  assessInfo.value.tsharScores = event.tsharScores
}

import { computed, ref, onMounted, reactive, onBeforeMount, nextTick } from "vue";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import { initRiskList, initCodePoint, addAssessInfo, queryAssess, queryEarly, deleteAssess, listPage, getOneAssess, updateData } from '@/api/secure/assessInfo'
import { mapListColumns, earlyColumns } from "@/views/secure/defect/assessInfo/config/columns";

import {
  mapOptions,
  dialogOptions,
  mapListFilters,
} from "@/views/secure/defect/assessInfo/config/filters";
import {
  ElMessage,
  ElTable
} from "element-plus";

import { useStore } from "vuex";
import { forEach } from "lodash";

// 获取登录用户信息
const { getters } = useStore();
// 用户信息
const UserInfo = computed(() => getters['user/getUserInfo']);

// const stores = useStore();
const ismapOptions = ref(mapOptions);
const thresholdDialogVisible = ref(false);
const viewDialogVisible = ref(false)

const addTilte = ref(""); // 弹出框名称

const rowId = ref(null)
const disabled = ref(true)

// 分页和数据展示参数
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);

const current2 = ref(1);
const pageSize2 = ref(10);
const total2 = ref(0);

const current3 = ref(1);
const pageSize3 = ref(10);
const total3 = ref(0);

const rows = ref({})

// 隐患清单弹窗数据
const riskTableData = ref([]);
// 信息列表数据
const tabledata = ref([
  {
    id: 202309190001,
    unitName: '维修单位一',
    total: '100',
    violation: '5',
    currentScore: '85',
    lastUpdateTime: '2021-05-10 14:27:30'
  }
]);
// 评分标注下拉框数据
const standards = ref([]);

const rowData = ref({})

const search = ref({
  unitNumber: null,
  unitName: null,
  updateTime: null
});
const pager2 = computed(() => ({
  currentPage: current2.value,
  pageSize: pageSize2.value,
  total: total2.value,
  pageCount:
    Math.ceil(total2.value / pageSize2.value) === 0
      ? 1
      : Math.ceil(total2.value / pageSize2.value),
}));

const pager = computed(() => ({
  currentPage: current3.value,
  pageSize: pageSize3.value,
  total: total3.value,
  pageCount:
    Math.ceil(total3.value / pageSize3.value) === 0
      ? 1
      : Math.ceil(total3.value / pageSize3.value),
}));

const earlyPager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  pageCount:
    Math.ceil(total.value / pageSize.value) === 0
      ? 1
      : Math.ceil(total.value / pageSize.value),
}));

// const asseeInfoRule =computed((rule)=>{
//    if (rule=='0') {
//      return "按期整改反馈并通过"
//    }  
//    if (rule=='1') {
//       return "未按期整改并进行反馈"
//    }
//    if (rule=='2') {
//       return "按期整改反馈但未通过完成隐患关闭"
//    }
// })

//按钮单选
const rowClickHandle = (row: any) => {

}

// 当用户手动勾选数据行的 Checkbox 时触发的事件
const selectChange = (selection: any, row: any) => {
  // 清除 所有勾选项
  earlyTable.value.clearSelection()
  if (selection.length == 0) return
  earlyTable.value.toggleRowSelection(row, true)

  getCodePoint(row, 1)
  earlySelect.value = row
}
// 当选择项发生变化时会触发该事件
const handleSelectionChange = (val: any) => {
  // console.log('表格的选中 可以获得当前选中的数据',val);
  // data.selectCheckList = val
  console.log(val)
  if (val == null || val.length <= 0) {
    //移除
    standards.value = {}
    assessInfo.value.tsharRules = ""
    assessInfo.value.tsharScores = ""
    earlySelect.value = []
  }
}


/**
 * @functionName 分页、查询、排序、删除功能
 * @author 杜思成
 * @date 2023-08-08 17:46:09
 * @version V1.0.0
 */
const changeCurrent = (value: number) => {
  current.value = value;
  let row = {
    id: rowId
  }
  getEarlyData(row)
};
const changeCurrent2 = (value: number) => {
  current2.value = value;
  getData()
};
//查看
const changeCurrent3 = (value: number) => {
  current3.value = value;
  searchData(rowData.value)
};



const changePageSize = (size: number) => {
  pageSize.value = size;
  let row = {
    id: rowId
  }
  getEarlyData(row)
};
const changePageSize2 = (size: number) => {
  pageSize2.value = size;
  getData()
};
const changePageSize3 = (size: number) => {
  pageSize3.value = size;
  searchData(rowData.value)
};
const order = ref([
  {
    column: "state",
    method: "asc",
  },
  {
    column: "lastUpdateTime",
    method: "desc",
  },
]);

onMounted(() => {
  getData()
})

/**
 * @functionName 获取数据
 */
const getData = async () => {
  const listParam = {
    tcdmSecureHazardAssessment: {
      tshaName: search.value.unitName != undefined ? search.value.unitName : null,
      tshaNumber: search.value.unitNumber != undefined ? search.value.unitNumber : null,
      valid: 1,
      // startTime: search.value.updateTime != undefined ? search.value.updateTime[0] : null,
      // endTime: search.value.updateTime != undefined ? search.value.updateTime[1] : null
    },
    page: {
      page: current2.value - 1,
      size: pageSize2.value
    },
    myTime2: {
      startTime: search.value.updateTime != undefined ? search.value.updateTime[0] : null,
      endTime: search.value.updateTime != undefined ? search.value.updateTime[1] : null
    }

  }
  listPage(listParam).then(res => {
    // if(res.code === '1') {
    tabledata.value = res.content
    total2.value = res.totalElements
    // }
  })
};

/**
 * 初始化评分规则
  */
const getCodePoint = (row: any, num: number) => {
  if (num == 1) {
    //移除
    assessInfo.value.tsharRules = ""
    assessInfo.value.tsharScores = ""
  }
  let grade = null;
  if (row.tshlGrade == "一般隐患") {
    grade = 1
  }
  if (row.tshlGrade == "严重隐患") {
    grade = 2
  }
  if (row.tshlGrade == "较大隐患") {
    grade = 3
  }
  const paramAssess = {
    tsharGrade: grade,
    tsharClassify: row.tshlClassify
  }
  queryAssess(paramAssess).then(res => {
    standards.value = res
    for (let i = 0; i < standards.value.length; i++) {
      if (standards.value[i].tsharRules == '0') {
        standards.value[i].rule = "按期整改反馈并通过"
      }
      if (standards.value[i].tsharRules == '1') {
        standards.value[i].rule = "未按期整改并进行反馈"
      }
      if (standards.value[i].tsharRules == '2') {
        standards.value[i].rule = "按期整改反馈但未通过完成隐患关闭"
      }
    }
    console.log(standards.value);

    disabled.value = false
    placeholder.value = "请选择"
  }).catch(res => {
  })
}

/**
 * @functionName 获取隐患数据
 */
const getEarlyData = async (row: any) => {
  const listParam = {
    page: {
      page: current.value - 1,
      size: pageSize.value,
    },
    tcdmSecureHazardList: {
      tshlUnit: row.tshaName,
      ischeck: 0
    },
    myTime2: {
      startTime: null,
      endTime: null
    }
  }
  initRiskList(listParam).then(res => {
    if (res) {
      for (let i = 0; i < res.content.length; i++) {
        if (res.content[i].tshlGrade == 1) {
          res.content[i].tshlGrade = '一般隐患';
        }
        if (res.content[i].tshlGrade == 2) {
          res.content[i].tshlGrade = '严重隐患'
        }
        if (res.content[i].tshlGrade == 3) {
          res.content[i].tshlGrade = '较大隐患'
        }
        // consle.log(res.content[i].assessmentRiteria)
        // if (res.content[i].assessmentRiteria == '0') {
        //   res.content[i].assessmentRiteria = '按期整改反馈并通过';
        // }
        // if (res.content[i].assessmentRiteria == '1') {
        //   res.content[i].assessmentRiteria = '未按期整改并进行反馈'
        // }
        // if (res.content[i].assessmentRiteria == '2') {
        //   res.content[i].assessmentRiteria = '按期整改反馈但未通过完成隐患关闭'
        // }
      }
      riskTableData.value = res.content

      total.value = res.totalElements
    }
  }).catch(res => {
    console.log(res)
  })
};

const save = () => {
  if (addTilte.value == "新建") {
    // console.log(earlySelect.value);
    const paramSava = {
      // createUserId: Number(UserInfo.value.userId),
      tshlId: earlySelect.value.tshlId,
      assessmentCode: assessInfo.value.tsharScores,
      ischeck: 1,
      // earlyId: earlySelect.value.id,
      assessmentRiteria: assessInfo.value.tsharRules
    }
    addAssessInfo(paramSava).then(res => {
      if (res) {
        ElMessage.success(res.message)
        thresholdDialogVisible.value = false
      } else {
        ElMessage.error(res.message)
      }
    }).catch(res => {

    })
  } else if (addTilte.value == "编辑") {
    // console.log(earlySelect.value)
    const paramUpdate = {
      itshlId: earlySelect.value.length <= 0 ? null : earlySelect.value.tshlId,
      assessmentCode: earlySelect.value.length <= 0 ? null : assessInfo.value.tsharScores,
      assessmentRiteria: earlySelect.value.length <= 0 ? null : assessInfo.value.tsharRules
    }
    console.log(paramUpdate)
    updateData(paramUpdate).then(res => {
      if (res) {
        ElMessage.success(res.message)
        thresholdDialogVisible.value = false
      } else {
        ElMessage.error(res.message)
      }
    })
  }

}

/**
 * @functionName 排序事件
 * @param {any} data 传入的某一列的列名和升降序
 * @author 彭庆楠
 * @date 2023-08-17 17:48:41
 * @version V1.0.0
 * @return
 */
const sortChange = (data: any) => {
  const method = data.order === "ascending" ? "asc" : "desc";
  order.value[0].column = data.prop;
  order.value[0].method = method;
  getData();
};
// 删除
const DeletRow = (row: any) => {
  const tcdmSecureHazardAssessment = {
    tshaId: row.tshaId
  }
  deleteAssess(tcdmSecureHazardAssessment).then(res => {
    // if (res.code === '1') {
    //   ElMessage.success(res.message)
    getData()
    // } else {
    //   ElMessage.error(res.message)
    // }
  })
};

/**
 * @functionName 新增、编辑弹出框
 * @param {any} val 判断打开那个弹窗
 * @description
 * @author 彭庆楠
 * @date 2023-08-08 17:53:22
 * @version V1.0.0
 * @return
 */
const handleCreate = (val: any, row: any) => {
  rowData.value = row
  disabled.value = true
  placeholder.value = "请选选择隐患清单"
  if (val === "create") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "新建";
    // ismapListFilters.value[0].defaultValue = '';
    // ismapListFilters.value[1].defaultValue = '';
  }
  if (val === "edit") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "编辑";
    // ismapListFilters.value[0].defaultValue = '';
    // ismapListFilters.value[1].defaultValue = '';
    const paramQuery = {
      //通过责任单位查询隐患清单
      page: {
        page: current.value - 1,
        size: pageSize.value,
      },
      tcdmSecureHazardList: {
        tshlUnit: row.tshaName,
        ischeck: 1
      },
      myTime2: {
        startTime: null,
        endTime: null
      }
    }
    queryEarly(paramQuery).then(res => {
      if (res) {
        for (let i = 0; i < res.content.length; i++) {
          if (res.content[i].tshlGrade == 1) {
            res.content[i].tshlGrade = '一般隐患';
          }
          if (res.content[i].tshlGrade == 2) {
            res.content[i].tshlGrade = '严重隐患'
          }
          if (res.content[i].tshlGrade == 3) {
            res.content[i].tshlGrade = '较大隐患'
          }
        }
        riskTableData.value = res.content
        total.value = res.totalElements
        const paramOne = {
          unitNumber: row.unitNumber,
        }
        // getOneAssess(paramOne).then(ress => {
        //   //回显
        //   if (ress.code === '1') {
        //     earlyTable.value.data.forEach(e => {
        //       if (e.assessId = ress.data) {
        //         rows.value = e
        //         earlySelect.value = e
        //       }
        //     });
        //     earlyTable.value.toggleRowSelection(rows.value, true)
        //     //回显评分标准、扣分值
        //     assessInfo.value.codePoint = ress.data.codePoint
        //     assessInfo.value.deductNumber = ress.data.deductNumber
        //     const paramCode = {
        //       earlyLevel: rows.value.earlyLevel
        //     }
        //     getCodePoint(paramCode, 0)

        //   }
        // })
      }
    })

  }
  if (val === "view") {
    // 弹窗标题
    viewDialogVisible.value = true;
    addTilte.value = "查看";
    // ismapListFilters.value[0].defaultValue = '';
    // ismapListFilters.value[1].defaultValue = '';
    searchData(row)
  }
};
const searchData = (row: any) => {
  const paramQuery = {
    page: {
      page: current.value - 1,
      size: pageSize.value,
    },
    tcdmSecureHazardList: {
      tshlUnit: row.tshaName,
      ischeck: 1
    },
    myTime2: {
      startTime: null,
      endTime: null
    }
  }
  queryEarly(paramQuery).then(res => {
    if (res) {
      for (let i = 0; i < res.content.length; i++) {
        if (res.content[i].tshlGrade == 1) {
          res.content[i].tshlGrade = '一般隐患';
        }
        if (res.content[i].tshlGrade == 2) {
          res.content[i].tshlGrade = '严重隐患'
        }
        if (res.content[i].tshlGrade == 3) {
          res.content[i].tshlGrade = '较大隐患'
        }
        if (res.content[i].assessmentRiteria == '0') {
          res.content[i].assessmentRiteria = '按期整改反馈并通过';
        }
        if (res.content[i].assessmentRiteria == '1') {
          res.content[i].assessmentRiteria = '未按期整改并进行反馈'
        }
        if (res.content[i].assessmentRiteria == '2') {
          res.content[i].assessmentRiteria = '按期整改反馈但未通过完成隐患关闭'
        }
      }
      riskTableData.value = res.content
      total3.value = res.totalElements
    }
  })
}
// 编辑
const handleEdit = async (row: any) => {
  handleCreate('edit', row)
};
// 新建
const handleAdd = async (row: any) => {
  getEarlyData(row)
  handleCreate('create', row)
  //清空输入框值
  standards.value = null
  assessInfo.value = {
    // 评分标准
    tsharClassify: '',
    tsharGrade: '',
    tsharRules: '',
    tsharScores: '',
  }
};
// 查看
const handleView = async (row: any) => {
  handleCreate('view', row)
};
const FilterRef = ref({});

/**
 * @functionName 重置功能
 * @param {FilterDataType} data
 * @description
 * @author 杜思成
 * @date 2023-08-17 17:55:57
 * @version V1.0.0
 * @return
 */
const searchReset = (data: FilterDataType) => {
  search.value = data;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData();
};
</script>

<style scoped>
:deep .el-checkbox__inner {
  border-radius: 50%;
}

:deep(.el-table__header .el-table__cell:first-child .el-checkbox) {
  visibility: hidden;
}

.link-btn {
  color: #2F7DF1;
}

.link-btns {
  color: #F24A45;
}
</style>
